<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多国家路网数据导入</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            background-color: #f5f5f5;
        }
        .import-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .content {
            padding: 20px;
        }
        .upload-section {
            margin-bottom: 30px;
        }
        .upload-area {
            border: 2px dashed #d9d9d9;
            border-radius: 6px;
            padding: 40px;
            text-align: center;
            background: #fafafa;
            transition: border-color 0.3s;
        }
        .upload-area:hover {
            border-color: #409eff;
        }
        .upload-area.is-dragover {
            border-color: #409eff;
            background: #f0f9ff;
        }
        .data-preview {
            margin-top: 20px;
        }
        .preview-table {
            max-height: 300px;
            overflow-y: auto;
        }
        .status-card {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .progress-section {
            margin-top: 20px;
        }
        .log-section {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            max-height: 200px;
            overflow-y: auto;
        }
        .log-item {
            margin-bottom: 5px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .log-info { color: #409eff; }
        .log-success { color: #67c23a; }
        .log-warning { color: #e6a23c; }
        .log-error { color: #f56c6c; }
        .template-section {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="import-container">
            <!-- 头部 -->
            <div class="header">
                <h1>多国家路网数据导入系统</h1>
                <p>支持从几何数据自动生成完整的路网信息</p>
            </div>

            <!-- 内容区域 -->
            <div class="content">
                <!-- 数据模板说明 -->
                <div class="template-section">
                    <h3>数据格式说明</h3>
                    <p><strong>必填字段:</strong></p>
                    <ul>
                        <li><code>geom</code> - 几何信息 WKT格式，如: <code>LINESTRING(116.4074 39.9042, 121.4737 31.2304)</code></li>
                    </ul>
                    <p><strong>可选字段:</strong></p>
                    <ul>
                        <li><code>name</code> - 道路名称</li>
                        <li><code>length</code> - 道路长度（米），不填会自动计算</li>
                        <li><code>source</code> - 起点节点ID，不填会自动生成</li>
                        <li><code>target</code> - 终点节点ID，不填会自动生成</li>
                        <li><code>source_point</code> - 起点坐标，不填会自动生成</li>
                        <li><code>target_point</code> - 终点坐标，不填会自动生成</li>
                    </ul>
                    <p><strong>示例数据:</strong></p>
                    <pre style="background: #f0f0f0; padding: 10px; border-radius: 4px; overflow-x: auto;">
[
  {
    "name": "京沪高速",
    "geom": "LINESTRING(116.4074 39.9042, 121.4737 31.2304)"
  },
  {
    "name": "京广高速", 
    "geom": "LINESTRING(116.4074 39.9042, 113.2644 23.1291)",
    "length": 2100.8
  }
]</pre>
                </div>

                <!-- 国家选择 -->
                <el-form :model="importForm" label-width="100px">
                    <el-form-item label="选择国家">
                        <el-select v-model="importForm.countryCode" placeholder="请选择国家" style="width: 200px">
                            <el-option 
                                v-for="country in countries" 
                                :key="country.code" 
                                :label="country.name" 
                                :value="country.code">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>

                <!-- 数据上传区域 -->
                <div class="upload-section">
                    <h3>数据上传</h3>
                    <div class="upload-area" 
                         :class="{ 'is-dragover': isDragOver }"
                         @drop="handleDrop"
                         @dragover="handleDragOver"
                         @dragleave="handleDragLeave">
                        <el-icon size="48" color="#c0c4cc"><Upload /></el-icon>
                        <p>将JSON文件拖拽到此处，或点击上传</p>
                        <p style="color: #999; font-size: 12px;">支持格式：JSON文件，包含geom字段的几何数据</p>
                        <el-button type="primary" @click="selectFile">选择文件</el-button>
                        <input ref="fileInput" type="file" accept=".json" style="display: none" @change="handleFileSelect">
                    </div>

                    <!-- 数据预览 -->
                    <div v-if="previewData" class="data-preview">
                        <h4>数据预览 (显示前10条)</h4>
                        <el-table :data="previewData.slice(0, 10)" size="small" border>
                            <el-table-column prop="name" label="名称" width="120"></el-table-column>
                            <el-table-column prop="geom" label="几何数据" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="length" label="长度" width="100"></el-table-column>
                        </el-table>
                        <p v-if="previewData.length > 10" style="text-align: center; color: #999;">
                            显示前10条，共{{ previewData.length }}条记录
                        </p>
                    </div>
                </div>

                <!-- 导入选项 -->
                <div v-if="previewData" class="status-card">
                    <h4>导入选项</h4>
                    <el-form :model="importForm" label-width="100px">
                        <el-form-item label="导入模式">
                            <el-radio-group v-model="importForm.importMode">
                                <el-radio label="append">追加导入</el-radio>
                                <el-radio label="replace">清空重新导入</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="数据验证">
                            <el-switch v-model="importForm.validateData" active-text="启用"></el-switch>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 导入进度 -->
                <div v-if="importing" class="progress-section">
                    <h4>导入进度</h4>
                    <el-progress :percentage="importProgress" :status="importStatus"></el-progress>
                    <p>{{ importMessage }}</p>
                </div>

                <!-- 操作按钮 -->
                <div style="text-align: center; margin-top: 30px;">
                    <el-button type="primary" @click="startImport" :loading="importing" :disabled="!previewData">
                        开始导入
                    </el-button>
                    <el-button @click="clearData" :disabled="importing">
                        清空数据
                    </el-button>
                    <el-button @click="validateData" :disabled="!previewData || importing">
                        验证数据
                    </el-button>
                    <el-button @click="resetForm" :disabled="importing">
                        重置
                    </el-button>
                </div>

                <!-- 导入日志 -->
                <div v-if="importLogs.length > 0" class="log-section">
                    <h4>导入日志</h4>
                    <div v-for="(log, index) in importLogs" :key="index" class="log-item" :class="'log-' + log.level">
                        [{{ log.time }}] {{ log.message }}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            data() {
                return {
                    baseURL: '/api',
                    countries: [],
                    importForm: {
                        countryCode: '',
                        importMode: 'append',
                        validateData: true
                    },
                    previewData: null,
                    isDragOver: false,
                    importing: false,
                    importProgress: 0,
                    importStatus: '',
                    importMessage: '',
                    importLogs: []
                }
            },
            mounted() {
                this.loadCountries();
            },
            methods: {
                // 加载国家列表
                async loadCountries() {
                    try {
                        const response = await axios.get(`${this.baseURL}/routing/countries`);
                        if (response.data.code === 200) {
                            this.countries = response.data.data;
                            if (this.countries.length > 0) {
                                this.importForm.countryCode = this.countries[0].code;
                            }
                        }
                    } catch (error) {
                        console.error('加载国家列表失败:', error);
                        ElMessage.error('加载国家列表失败');
                    }
                },

                // 选择文件
                selectFile() {
                    this.$refs.fileInput.click();
                },

                // 处理文件选择
                handleFileSelect(event) {
                    const file = event.target.files[0];
                    if (file) {
                        this.processFile(file);
                    }
                },

                // 处理拖拽
                handleDragOver(event) {
                    event.preventDefault();
                    this.isDragOver = true;
                },

                handleDragLeave(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                },

                handleDrop(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                    const files = event.dataTransfer.files;
                    if (files.length > 0) {
                        this.processFile(files[0]);
                    }
                },

                // 处理文件
                async processFile(file) {
                    if (!file.name.endsWith('.json')) {
                        ElMessage.error('请选择JSON文件');
                        return;
                    }

                    try {
                        const text = await file.text();
                        const data = JSON.parse(text);
                        
                        // 验证数据格式
                        if (!Array.isArray(data)) {
                            ElMessage.error('数据格式不正确，应该是数组格式');
                            return;
                        }

                        this.previewData = data;
                        ElMessage.success('文件解析成功');
                        this.addLog('info', '文件解析成功: ' + file.name);

                    } catch (error) {
                        console.error('文件处理失败:', error);
                        ElMessage.error('文件处理失败: ' + error.message);
                        this.addLog('error', '文件处理失败: ' + error.message);
                    }
                },

                // 验证数据
                async validateData() {
                    if (!this.previewData) {
                        ElMessage.error('请先上传数据文件');
                        return;
                    }

                    try {
                        const response = await axios.post(`${this.baseURL}/routing/data/validate`, this.previewData);
                        if (response.data.code === 200) {
                            const result = response.data.data;
                            if (result.valid) {
                                ElMessage.success(`数据验证通过 (${result.warningCount} 个警告)`);
                            } else {
                                ElMessage.error(`数据验证失败 (${result.errorCount} 个错误)`);
                            }
                            this.addLog('info', `数据验证完成: ${result.errorCount} 个错误, ${result.warningCount} 个警告`);
                        }
                    } catch (error) {
                        console.error('数据验证失败:', error);
                        ElMessage.error('数据验证失败: ' + error.message);
                    }
                },

                // 开始导入
                async startImport() {
                    if (!this.importForm.countryCode) {
                        ElMessage.error('请选择国家');
                        return;
                    }

                    if (!this.previewData) {
                        ElMessage.error('请先上传数据文件');
                        return;
                    }

                    try {
                        await ElMessageBox.confirm(
                            `确定要${this.importForm.importMode === 'replace' ? '清空并重新' : ''}导入 ${this.countries.find(c => c.code === this.importForm.countryCode)?.name} 的路网数据吗？`,
                            '确认导入',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }
                        );

                        this.importing = true;
                        this.importProgress = 0;
                        this.importStatus = '';
                        this.importMessage = '准备导入...';
                        this.importLogs = [];

                        await this.performImport();

                    } catch (error) {
                        if (error !== 'cancel') {
                            console.error('导入失败:', error);
                            ElMessage.error('导入失败: ' + error.message);
                        }
                    }
                },

                // 执行导入
                async performImport() {
                    try {
                        this.addLog('info', '开始导入数据...');
                        this.updateProgress(10, '正在验证数据...');

                        // 选择导入接口
                        const url = this.importForm.importMode === 'replace' 
                            ? `${this.baseURL}/routing/data/import/clear`
                            : `${this.baseURL}/routing/data/import`;

                        this.updateProgress(30, '正在上传数据...');

                        const response = await axios.post(url, this.previewData, {
                            params: { countryCode: this.importForm.countryCode },
                            timeout: 300000 // 5分钟超时
                        });

                        if (response.data.code === 200) {
                            this.updateProgress(100, '导入完成', 'success');
                            this.addLog('success', response.data.msg);
                            ElMessage.success('数据导入成功');
                        } else {
                            throw new Error(response.data.msg || '导入失败');
                        }

                    } catch (error) {
                        this.updateProgress(0, '导入失败', 'exception');
                        this.addLog('error', '导入失败: ' + error.message);
                        ElMessage.error('导入失败: ' + error.message);
                    } finally {
                        this.importing = false;
                    }
                },

                // 清空数据
                async clearData() {
                    if (!this.importForm.countryCode) {
                        ElMessage.error('请选择国家');
                        return;
                    }

                    try {
                        await ElMessageBox.confirm(
                            `确定要清空 ${this.countries.find(c => c.code === this.importForm.countryCode)?.name} 的路网数据吗？`,
                            '确认清空',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }
                        );

                        const response = await axios.post(`${this.baseURL}/routing/data/clear`, null, {
                            params: { countryCode: this.importForm.countryCode }
                        });

                        if (response.data.code === 200) {
                            ElMessage.success('数据清空成功');
                        } else {
                            throw new Error(response.data.msg || '清空失败');
                        }

                    } catch (error) {
                        if (error !== 'cancel') {
                            console.error('清空失败:', error);
                            ElMessage.error('清空失败: ' + error.message);
                        }
                    }
                },

                // 重置表单
                resetForm() {
                    this.previewData = null;
                    this.importing = false;
                    this.importProgress = 0;
                    this.importStatus = '';
                    this.importMessage = '';
                    this.importLogs = [];
                    this.$refs.fileInput.value = '';
                },

                // 更新进度
                updateProgress(progress, message, status = '') {
                    this.importProgress = progress;
                    this.importMessage = message;
                    this.importStatus = status;
                },

                // 添加日志
                addLog(level, message) {
                    const time = new Date().toLocaleTimeString();
                    this.importLogs.push({ time, level, message });
                }
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
